package com.diandian.backend.jingdong.home.exchange.service;

import com.alibaba.fastjson.JSON;
import com.diandian.backend.jingdong.home.exchange.req.SkuStockUpdateOneReq;
import com.diandian.base.boot.starter.exception.DefaultException;
import com.diandian.jingdong.home.boot.starter.dto.WebResponseDTO;
import com.diandian.jingdong.home.boot.starter.service.stock.JingdongStockInBasicService;
import com.diandian.jingdong.home.boot.starter.service.stock.dto.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BusinessStockInService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessStockInService.class);

    @Autowired
    private JingdongStockInBasicService stockInBasicService;

    @Autowired
    private BusinessDataTransferService businessDataTransferService;

    /**
     * 同步单个商品现货库存
     * @param data
     * @throws Exception
     */
    public WebResponseDTO skuStockUpdateOne(String appKey, String appSecret, String token, String operator, String belong, SkuStockUpdateOneReq data) throws Exception {

        // 1. 参数检查
        if (!data.check()) {
            logger.info("更新单个库存时参数缺失，数据：{}", JSON.toJSONString(data));
            throw new DefaultException(1, "更新单个库存时参数缺失");
        }
        String offlineStoreCode = data.getOfflineStoreCode();
        String productCode = data.getProductCode();
        int stockCount = data.getStockCount();

        // 2. 通过线下编码查询线上编码，不存在时停止同步
        String onlineStoreCode = businessDataTransferService.offlineCodeToOnlineCode(belong, offlineStoreCode);

        // 3. 查询线上门店是否有此商品，无则停止同步(因为使用了总部商品库，暂不放开此逻辑)
//        ProductGetSkuByOuterSkuIdsResponse response = productQueryBasicService.getSkuByOuterSkuIds(appKey, appSecret, token, Arrays.asList(productCode));
//        if(response == null || response.getResult() == null || response.getResult().size() == 0) {
//            logger.info("更新单个库存时商品不存在，数据：{}", JSON.toJSONString(data));
//            return;
//        }

        // 4. 执行同步操作
        WebResponseDTO syncResponse = null;
        try{
            List<BatchUpdateCurrentQtysDTOSkuStock> skuStockDataList = Arrays.asList(new BatchUpdateCurrentQtysDTOSkuStock(productCode, stockCount));
            BatchUpdateCurrentQtysDTO qtysDTO = new BatchUpdateCurrentQtysDTO();
            qtysDTO.setStationNo(onlineStoreCode);
            qtysDTO.setSkuStockList(skuStockDataList);
            qtysDTO.setUserPin(operator);
            syncResponse = stockInBasicService.batchUpdateCurrentQtys(appKey, appSecret, token, operator, qtysDTO);
            logger.info("更新单个商品库存完成，执行参数: {}，执行结果：{}", JSON.toJSONString(qtysDTO), JSON.toJSONString(syncResponse));
        } catch (Exception e){
            logger.error("向京东推送库存数据时出现异常", e);
        }

        return syncResponse;
    }

    /**
     * 同步单个商品可用库存
     * @param data
     * @throws Exception
     */
    public WebResponseDTO skuStockUpdateUsableStock(String appKey, String appSecret, String token, String operator, String belong, SkuStockUpdateOneReq data) throws Exception {

        // 参数检查
        if (!data.check()) {
            logger.info("更新单个可用库存时参数缺失，数据：{}", JSON.toJSONString(data));
            throw new DefaultException(1, "更新单个库存时参数缺失");
        }
        String storeCode = data.getOfflineStoreCode();
        int stockCount = data.getStockCount();
        String productCode = data.getProductCode();

        // 通过线下编码查询线上编码，不存在时停止同步
        String onlineStoreCode = businessDataTransferService.offlineCodeToOnlineCode(belong, storeCode);

        // 根据商家skuId获取京东skuId
        Long djSkuId = businessDataTransferService.localSkuIdToDjSkuId(appKey, appSecret, token, onlineStoreCode, productCode);
        if(djSkuId == null) {
            logger.info("更新单个可用库存时商品信息缺失，参数: {}, 商家skuId：{}", JSON.toJSONString(data), productCode);
            throw new DefaultException(1, "更新单个库存时商品信息缺失");
        }

        // 执行同步操作
        WebResponseDTO syncResponse = null;
        try{
            List<BatchUpdateUsableQtyNewDTOStock> skuStockDataList = Arrays.asList(new BatchUpdateUsableQtyNewDTOStock(djSkuId, onlineStoreCode, stockCount));
            BatchUpdateUsableQtyNewDTO stockData = new BatchUpdateUsableQtyNewDTO();
            stockData.setQueryStockRequests(skuStockDataList);
            stockData.setCurUserPin(operator);
            syncResponse = stockInBasicService.batchUpdateUsableQty(appKey, appSecret, token, operator, stockData);
            logger.info("更新单个商品可用库存完成，执行参数: {}，执行结果：{}", JSON.toJSONString(data), JSON.toJSONString(syncResponse));
        } catch (Exception e){
            logger.error("向京东推送库存数据时出现异常", e);
        }

        return syncResponse;
    }
}
